#include "HttpServer.h"
#include <iostream>
#include <thread>
#include <chrono>

using std::cout;
using std::endl;

int main() {
    // 创建HTTP服务器：4个SubReactor，8个工作线程，队列大小1024
    HttpServer server("127.0.0.1", 8080, 4, 8, 1024);
    
    // 注册路由
    
    // GET /hello - 简单的Hello World
    server.get("/hello", [](const HttpRequest& req, HttpResponse& resp) {
        resp.setJsonContent(R"({"message": "Hello, World!", "method": "GET"})");
    });
    
    // GET /api/status - API状态
    server.get("/api/status", [](const HttpRequest& req, HttpResponse& resp) {
        resp.setJsonContent(R"({
            "status": "ok", 
            "server": "MultiReactorHttpServer",
            "version": "1.0",
            "timestamp": ")" + std::to_string(std::time(nullptr)) + R"("
        })");
    });
    
    // GET /user/:id - 路径参数示例（简化版，不支持参数提取）
    server.get("/user/.*", [](const HttpRequest& req, HttpResponse& resp) {
        std::string path = req.getPath();
        std::string userId = path.substr(path.find_last_of('/') + 1);
        
        resp.setJsonContent(R"({
            "userId": ")" + userId + R"(",
            "name": "User )" + userId + R"(",
            "email": "user)" + userId + R"(@example.com"
        })");
    });
    
    // POST /api/echo - 回显POST数据
    server.post("/api/echo", [](const HttpRequest& req, HttpResponse& resp) {
        resp.setJsonContent(R"({
            "echo": ")" + req.getBody() + R"(",
            "method": "POST",
            "path": ")" + req.getPath() + R"("
        })");
    });
    
    // GET /api/headers - 显示所有请求头
    server.get("/api/headers", [](const HttpRequest& req, HttpResponse& resp) {
        std::ostringstream json;
        json << "{\"headers\": {";
        
        bool first = true;
        for (const auto& header : req.getAllHeaders()) {
            if (!first) json << ", ";
            json << "\"" << header.first << "\": \"" << header.second << "\"";
            first = false;
        }
        
        json << "}}";
        resp.setJsonContent(json.str());
    });
    
    // GET /api/query - 显示查询参数
    server.get("/api/query", [](const HttpRequest& req, HttpResponse& resp) {
        std::ostringstream json;
        json << "{\"queries\": {";
        
        bool first = true;
        for (const auto& query : req.getAllQueries()) {
            if (!first) json << ", ";
            json << "\"" << query.first << "\": \"" << query.second << "\"";
            first = false;
        }
        
        json << "}}";
        resp.setJsonContent(json.str());
    });
    
    // GET / - 主页HTML
    server.get("/", [](const HttpRequest& req, HttpResponse& resp) {
        std::string html = R"(<!DOCTYPE html>
<html>
<head>
    <title>Multi-Reactor HTTP Server</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .endpoint { background: #f0f0f0; padding: 10px; margin: 10px 0; border-radius: 5px; }
        .method { font-weight: bold; color: #007acc; }
    </style>
</head>
<body>
    <h1>🚀 Multi-Reactor HTTP Server</h1>
    <p>基于多Reactor + 线程池架构的高性能HTTP服务器</p>
    
    <h2>可用的API端点：</h2>
    
    <div class="endpoint">
        <span class="method">GET</span> /hello - Hello World JSON响应
    </div>
    
    <div class="endpoint">
        <span class="method">GET</span> /api/status - 服务器状态信息
    </div>
    
    <div class="endpoint">
        <span class="method">GET</span> /user/123 - 用户信息（路径参数）
    </div>
    
    <div class="endpoint">
        <span class="method">POST</span> /api/echo - 回显POST数据
    </div>
    
    <div class="endpoint">
        <span class="method">GET</span> /api/headers - 显示所有请求头
    </div>
    
    <div class="endpoint">
        <span class="method">GET</span> /api/query?name=value - 显示查询参数
    </div>
    
    <h2>测试命令：</h2>
    <pre>
# 基本GET请求
curl http://localhost:8080/hello

# 带查询参数
curl "http://localhost:8080/api/query?name=test&age=25"

# POST请求
curl -X POST -d "Hello Server" http://localhost:8080/api/echo

# 查看请求头
curl -H "X-Test: MyValue" http://localhost:8080/api/headers
    </pre>
</body>
</html>)";
        resp.setHtmlContent(html);
    });
    
    // 添加日志中间件
    server.use([](const HttpRequest& req, HttpResponse& resp) -> bool {
        cout << "[" << std::time(nullptr) << "] " 
             << req.getMethodString() << " " << req.getPath() << endl;
        return true; // 继续处理
    });
    
    cout << "=== Multi-Reactor HTTP Server ===" << endl;
    cout << "监听地址: http://127.0.0.1:8080" << endl;
    cout << "架构配置:" << endl;
    cout << "- 主Reactor: 1个 (处理新连接)" << endl;
    cout << "- 从Reactor: 4个 (处理I/O事件)" << endl;
    cout << "- 线程池: 8个工作线程 (处理业务逻辑)" << endl;
    cout << "============================" << endl;
    cout << "访问 http://localhost:8080 查看可用API" << endl;
    cout << "按 Ctrl+C 停止服务器" << endl;
    
    // 启动服务器
    server.start();
    
    return 0;
}